package com.lanren.familybookapp.ui.home.view;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanren.common.interfaces.AdapterItemClickView;
import com.lanren.common.utils.DateUtils;
import com.lanren.common.utils.GsonUtils;
import com.lanren.common.utils.KeyboardUtils;
import com.lanren.common.utils.ScreenUtils;
import com.lanren.common.utils.StringUtils;
import com.lanren.common.utils.Utils;
import com.lanren.common.utils.event.C;
import com.lanren.common.widget.ClearEditText;
import com.lanren.common.widget.SwitchMultiButton;
import com.lanren.common.widget.TitleBarView;
import com.lanren.common.widget.gridviewpager.GridViewPager;
import com.lanren.common.widget.pickerview.TimePickerDialog;
import com.lanren.common.widget.pickerview.data.Type;
import com.lanren.common.widget.pickerview.listener.OnDateSetListener;
import com.lanren.easydialog.DialogViewHolder;
import com.lanren.easydialog.EasyDialog;
import com.lanren.easyeventbus.Event;
import com.lanren.easyeventbus.EventBusUtil;
import com.lanren.familybookapp.R;
import com.lanren.familybookapp.app.AppUserHelper;
import com.lanren.familybookapp.app.MyApplication;
import com.lanren.familybookapp.base.BaseUiActivity;
import com.lanren.familybookapp.ui.home.adapter.BookMemberAdapter;
import com.lanren.familybookapp.ui.home.adapter.BookPayTypeAdapter;
import com.lanren.familybookapp.ui.home.bean.BookClassifyBean;
import com.lanren.familybookapp.ui.home.bean.BookPayTypeBean;
import com.lanren.familybookapp.ui.home.interfaces.IBookkeepingAddModel;
import com.lanren.familybookapp.ui.home.model.BookkeepingAddModel;
import com.lanren.familybookapp.ui.home.presenter.BookkeepingAddPresenter;
import com.lanren.familybookapp.ui.me.bean.BookInfoBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

/**
 * @ClassName BookkeepingAddActivity
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2020/2/14 13:44
 * @Version 1.0
 */
public class BookkeepingAddActivity extends BaseUiActivity<BookkeepingAddPresenter> implements IBookkeepingAddModel.IBookkeepingEditView {

    @BindView(R.id.title_view)
    TitleBarView titleView;
    @BindView(R.id.book_inout)
    SwitchMultiButton bookInout;
    @BindView(R.id.book_classify_list)
    GridViewPager bookClassifyList;
    @BindView(R.id.book_classify_img)
    TextView bookClassifyImg;
    @BindView(R.id.book_classify_name)
    TextView bookClassifyName;
    @BindView(R.id.book_money)
    EditText bookMoney;
    @BindView(R.id.et_goods)
    ClearEditText etGoods;
    @BindView(R.id.book_time)
    TextView bookTime;
    @BindView(R.id.book_time_view)
    LinearLayout bookTimeView;
    @BindView(R.id.et_member)
    EditText etMember;
    @BindView(R.id.book_member_view)
    LinearLayout bookMemberView;
    @BindView(R.id.et_pay_type)
    EditText etPayType;
    @BindView(R.id.book_pay_type_view)
    LinearLayout bookPayTypeView;
    @BindView(R.id.et_ps)
    EditText etPs;
    @BindView(R.id.book_save)
    Button bookSave;

    private TimePickerDialog mDialogYearMonth;
    private String mInOut = "支出";
    private String mBookCreateUser;


    private BookMemberAdapter bookMemberAdapter;
    private List<Map<String, String>> bookMemberList = new ArrayList<>();

    private BookPayTypeAdapter bookPayTypeAdapter;
    private List<BookPayTypeBean> bookPayTypeList = new ArrayList<>();

    private List<BookClassifyBean> bookClassifyBeanList = new ArrayList<>();

    @Override
    public BookkeepingAddPresenter createPresenter() {
        return new BookkeepingAddPresenter(new BookkeepingAddModel());
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_add_bookkeeping;
    }

    @Override
    public void doCreate(Bundle savedInstanceState) {
        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        mDialogYearMonth = new TimePickerDialog.Builder()
                .setThemeColor(getResources().getColor(R.color.green10))
                .setTitleStringId("选择时间")
                .setMinMillseconds(DateUtils.rollYear(new Date(), -20).getTime())
                .setMaxMillseconds(DateUtils.rollDay(new Date(), 7).getTime())
                .setCurrentMillseconds(DateUtils.getNowTime())
                .setType(Type.ALL)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        bookTime.setText(DateUtils.longToFormat(millseconds, "yyyy-MM-dd HH:mm"));
                    }
                })
                .setCyclic(false)
                .build();

        bookMemberAdapter = new BookMemberAdapter(this, bookMemberList);
        bookPayTypeAdapter = new BookPayTypeAdapter(this, bookPayTypeList);
    }

    @Override
    public void initData() {
        bookInout.setText("支出", "收入");
        bookInout.setSelectedTab(0);
        bookTime.setText(DateUtils.longToFormat(DateUtils.getNowTime(), "yyyy-MM-dd HH:mm"));
        mPresenter.getBookInfo(AppUserHelper.getInstance().getUser().getUserUseBook());


        bookClassifyList.setDataAllCount(bookClassifyBeanList.size())
                .setImageTextLoaderInterface(new GridViewPager.ImageTextLoaderInterface() {
                    @Override
                    public void displayImageText(TextView imageView, TextView textView, int position) {
                        imageView.setText(bookClassifyBeanList.get(position).getClassify().substring(0, 1));
                        textView.setText(bookClassifyBeanList.get(position).getClassify());
                    }
                })
                .setGridItemClickListener(new GridViewPager.GridItemClickListener() {
                    @Override
                    public void click(int position) {
                        bookClassifyImg.setText(bookClassifyBeanList.get(position).getClassify().substring(0, 1));
                        bookClassifyName.setText(bookClassifyBeanList.get(position).getClassify());
                    }
                }).show();

    }

    @Override
    public void initEvent() {
        titleView.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        bookInout.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                mInOut = tabText;
                if (position == 0) {
                    bookMoney.setTextColor(Color.parseColor("#FF0000"));
                } else {
                    bookMoney.setTextColor(Color.parseColor("#4BBF8E"));
                }
            }
        });

        bookMoney.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (EditorInfo.IME_ACTION_DONE == actionId) {//在点击回车键后隐藏输入法
                    KeyboardUtils.hideInputMethod(BookkeepingAddActivity.this, v);
                }
                return false;
            }
        });

    }


    @OnClick({R.id.book_time_view, R.id.book_member_view, R.id.book_pay_type_view, R.id.book_save, R.id.et_member, R.id.et_pay_type})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.book_time_view:
                if (Utils.isFastClick(view)) {
                    mDialogYearMonth.show(this);
                }
                break;
            case R.id.et_member:
            case R.id.book_member_view:
                if (Utils.isFastClick(view)) {
                    showMemberSele();
                }
                break;
            case R.id.et_pay_type:
            case R.id.book_pay_type_view:
                if (Utils.isFastClick(view)) {
                    showPaytypeSele();
                }
                break;
            case R.id.book_save:
                if (Utils.isFastClick(view, 3200)) {
                    mPresenter.addBookkeeping(AppUserHelper.getInstance().getUser().getUserUseBook(),
                            bookClassifyName.getText().toString(),
                            bookMoney.getText().toString(),
                            mInOut,
                            etGoods.getText().toString(),
                            bookTime.getText().toString(),
                            etMember.getText().toString(),
                            etPayType.getText().toString(),
                            etPs.getText().toString());
                }
                break;
        }
    }


    private void showMemberSele() {
        new EasyDialog(this, R.layout.dialog_book_member_paytype) {
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                holder.getView(R.id.book_paytype).setVisibility(View.GONE);
                holder.getView(R.id.tv_sure).setVisibility(View.GONE);
                holder.setOnClick(R.id.tv_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
                RecyclerView bookList = holder.getView(R.id.book_member_paytype_list);
                bookList.setLayoutManager(new LinearLayoutManager(BookkeepingAddActivity.this));
                bookList.setAdapter(bookMemberAdapter);
                bookMemberAdapter.setDele(false);

                bookMemberAdapter.setAdapterItemClickView(new AdapterItemClickView() {
                    @Override
                    public void onItemClick(int pointion) {
                        etMember.setText(bookMemberList.get(pointion).get("userInvite"));
                        dismiss();
                    }

                    @Override
                    public void onItemClick(int pointion, View view) {

                    }

                    @Override
                    public void onItemLongClick(int pointion) {

                    }

                    @Override
                    public void onItemLongClick(int pointion, View view) {

                    }
                });
            }
        }
                .setCanceledOnTouchOutside(false)
                .setCancelAble(false)
                .backgroundLight(0.2)
                .setWidthAndHeight(MATCH_PARENT, ScreenUtils.getScreenHeight(MyApplication.getApp()) / 2)
                .fromBottom()
                .fullWidth()
                .showDialog();
    }


    private void showPaytypeSele() {
        new EasyDialog(this, R.layout.dialog_book_member_paytype) {
            @Override
            public void onBindViewHolder(DialogViewHolder holder) {
                final EditText editText = holder.getView(R.id.book_paytype);
                RecyclerView bookList = holder.getView(R.id.book_member_paytype_list);
                bookList.setLayoutManager(new LinearLayoutManager(BookkeepingAddActivity.this));
                bookList.setAdapter(bookPayTypeAdapter);
                if (bookPayTypeList.size() > 0) {
                    if (AppUserHelper.getInstance().getUser().getUserId().equals(bookPayTypeList.get(0).getBookCreateUser())) {
                        holder.getView(R.id.book_paytype).setVisibility(View.VISIBLE);
                        holder.getView(R.id.tv_sure).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.book_paytype).setVisibility(View.GONE);
                        holder.getView(R.id.tv_sure).setVisibility(View.GONE);
                    }
                    bookPayTypeAdapter.notifyDataSetChanged();
                }
                holder.setOnClick(R.id.tv_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                }).setOnClick(R.id.tv_sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String paytype = editText.getText().toString();
                        if (StringUtils.isNotBlank(paytype)) {
                            mPresenter.addBookPaytype(mBookCreateUser, paytype);
                            editText.setText("");
                        }
                    }
                });

                bookPayTypeAdapter.setAdapterItemClickView(new AdapterItemClickView() {
                    @Override
                    public void onItemClick(int pointion) {
                        mPresenter.delBookPaytype(bookPayTypeList.get(pointion).getId(), pointion);
                    }

                    @Override
                    public void onItemClick(int pointion, View view) {
                        etPayType.setText(bookPayTypeList.get(pointion).getPayType());
                        dismiss();
                    }

                    @Override
                    public void onItemLongClick(int pointion) {

                    }

                    @Override
                    public void onItemLongClick(int pointion, View view) {

                    }
                });
            }
        }
                .setCanceledOnTouchOutside(false)
                .setCancelAble(false)
                .backgroundLight(0.2)
                .setWidthAndHeight(MATCH_PARENT, ScreenUtils.getScreenHeight(MyApplication.getApp()) / 2)
                .fromBottom()
                .fullWidth()
                .showDialog();
    }

    @Override
    public void showError(int code, String msg) {
        super.showError(code, msg);
    }

    @Override
    public void onSuccessBook(String msg) {
        showMessage(msg);
    }

    @Override
    public void onSuccessBook(int code, String msg, int pointion) {
        if (code == 100) {
            getBookPaytypeList(mBookCreateUser);
        } else if (code == 101) {
            bookPayTypeAdapter.remove(pointion);
        } else if (code == 200) {
            EventBusUtil.sendEvent(new Event(C.EventCode.REFRESH_HOME));
            finish();
        }
    }

    @Override
    public void onSuccessClassify(List<BookClassifyBean> bookClassifyBeans) {
        if (bookClassifyBeans.size() > 0) {
            bookClassifyBeanList.clear();
        }
        bookClassifyBeanList.addAll(bookClassifyBeans);
        bookClassifyList.setDataAllCount(bookClassifyBeans.size()).setColumnCount(5).setRowCount(3).show();
    }

    @Override
    public void onSuccessBookInfo(List<BookInfoBean> bookInfoBeans) {
        BookInfoBean bookInfoBean = bookInfoBeans.get(0);
        mBookCreateUser = bookInfoBean.getBookCreateUser();
        List<Map<String, String>> mapList = GsonUtils.fromJsonToListMaps(bookInfoBean.getUserInvite());

        if (bookMemberList.size() > 0) {
            bookMemberList.clear();
        }
        bookMemberList.addAll(mapList);

        getBookClassify(bookInfoBean.getBookCreateUser());
        getBookPaytypeList(bookInfoBean.getBookCreateUser());
    }

    @Override
    public void onSuccessPayType(List<BookPayTypeBean> bookPayTypeBeans) {
        if (bookPayTypeList.size() > 0) {
            bookPayTypeList.clear();
        }
        bookPayTypeList.addAll(bookPayTypeBeans);
        bookPayTypeAdapter.notifyDataSetChanged();
    }

    private void getBookClassify(String bookCreateUser) {
        mPresenter.getBookClassify(bookCreateUser);
    }

    private void getBookPaytypeList(String bookCreateUser) {
        mPresenter.getBookPaytypeList(bookCreateUser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDialogYearMonth != null) {
            mDialogYearMonth.clearDialog();
            mDialogYearMonth = null;
        }
    }
}
